package com.sweets.look.ui.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.sweet.satellite.GlobalConfig;
import com.sweet.satellite.TranslucentSBActivity;
import com.sweets.look.R;
import com.sweets.look.constant.Constants;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.BaseActivity;
import com.sweets.look.ui.setting.GeneralSettings;
import com.sweets.look.ui.view.CardPickerDialog;
import com.sweets.look.ui.widget.MarkDialog;
import com.sweets.look.util.BrowserUtils;
import com.sweets.look.util.LogUtils;
import com.sweets.look.util.ThemeHelper;
import com.sweets.look.util.Utils;
import com.sweets.look.util.ViewHelper;
import com.sweets.look.util.ViewUtils;
import com.xiaomi.mistatistic.sdk.MiStatInterface;

/**
 * Author   Shone
 * Date     21/07/16.
 * Github   https://github.com/shonegg
 */
public class MainActivity extends BaseActivity {

    public static String ACTION = "com.action.change.theme";
    private ImageView mHomeBg;

    public class UIReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION.equals(action)) {
                switchDayOrNight();
            }
        }
    }

    protected void setTranslucentNavigation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        }
    }


    private ImageView mMenuNight;
    private ImageView mMenuFullScreen;
    private PreferenceManager mPreferences;
    private ImageView mMenuSetting;
    private Context mContext;
    private RelativeLayout mHomeSearch;
    private ImageView mHomeSerachBt;
    private ImageView mActionIncognito;
    private ImageView mHomeScan;
    private UIReceiver receiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTranslucentNavigation();
        setContentView(R.layout.activity_main);
        mContext = this;
        initMenu();

        IntentFilter filter = new IntentFilter(ACTION);
        receiver = new UIReceiver();
        registerReceiver(receiver, filter);
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }


    @Override
    protected void onResume() {
        super.onResume();
        MiStatInterface.recordPageStart(this, "主界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MiStatInterface.recordPageEnd();
    }

    private void initMenu() {
        mHomeBg = (ImageView) findViewById(R.id.home_bg);
        mHomeSearch = (RelativeLayout) findViewById(R.id.home_search);
        mHomeSerachBt = (ImageView) findViewById(R.id.home_serach_bt);
        mMenuSetting = (ImageView) findViewById(R.id.home_menu);
        mMenuNight = (ImageView) findViewById(R.id.action_night);
        mMenuFullScreen = (ImageView) findViewById(R.id.action_fullscreen);
        mActionIncognito = (ImageView) findViewById(R.id.action_incognito);
        mHomeScan = (ImageView) findViewById(R.id.home_scan);

        this.mPreferences = PreferenceManager.getInstance();
        switchDayOrNight();

        ViewUtils.setImageTint(mPreferences.getNightModeEnabled() ?
                        this.getResources().getColor(R.color.teal)
                        : this.getResources().getColor(R.color.app_color),
                new ImageView[]{this.mMenuNight});
        ViewUtils.setImageTint(this.mPreferences.getHideStatusBarEnabled() ?
                        this.getResources().getColor(R.color.teal)
                        : this.getResources().getColor(R.color.app_color),
                new ImageView[]{this.mMenuFullScreen});
        ViewUtils.setImageTint(this.getResources().getColor(R.color.app_color),
                new ImageView[]{this.mMenuSetting});
        ViewUtils.setImageTint(this.mPreferences.getIncognitoModeEnabled() ?
                this.getResources().getColor(R.color.teal)
                : this.getResources().getColor(R.color.app_color), new ImageView[]{this.mActionIncognito});

        initializePreferences();
    }

    private synchronized void initializePreferences() {
        ViewHelper.switchFullScreenMode(this);//是否全屏显示

        this.mPreferences = PreferenceManager.getInstance();
        switch (this.mPreferences.getScreenOrientation()) {//屏幕方向
            case 1: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);//2
                break;
            }
            case 2: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);//10
                break;
            }
            case 3: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//1
                break;
            }
            case 4: {
                this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//0
                break;
            }
        }
    }

    public void onMenuBtnClick(View view) {
        switch (view.getId()) {
            case R.id.home_book: {
                Intent intent = new Intent(this.mContext, BrowserActivity.class);
                intent.putExtra("cmd_bookmark", true);
                this.startActivity(intent);
                break;
            }
            case R.id.home_menu: {
                this.startActivity(new Intent(this.mContext, GeneralSettings.class));
                break;
            }
            case R.id.action_night: {
                mPreferences.setNightModeEnabled(!this.mPreferences.getNightModeEnabled());
                this.switchDayOrNight();
                ViewUtils.setImageTint(this.mPreferences.getNightModeEnabled() ?
                        this.getResources().getColor(R.color.teal) :
                        this.getResources().getColor(R.color.app_color), new ImageView[]{this.mMenuNight});
                break;
            }
            case R.id.action_fullscreen: {
                mPreferences.setHideStatusBarEnabled(!this.mPreferences.getHideStatusBarEnabled());
                ViewHelper.switchFullScreenMode(MainActivity.this);
                String toast = this.mPreferences.getHideStatusBarEnabled() ? this.getResources().getString(
                        R.string.toast_fullscreen_on) : this.getResources().getString(R.string.toast_fullscreen_off);
                ViewUtils.showToast(findViewById(R.id.root_layout), toast);

                ViewUtils.setImageTint(this.mPreferences.getHideStatusBarEnabled() ?
                        this.getResources().getColor(R.color.teal)
                        : this.getResources().getColor(R.color.app_color), new ImageView[]{this.mMenuFullScreen});
                break;
            }
            case R.id.action_incognito: {
                mPreferences.setIncognitoModeEnabled(!this.mPreferences.getIncognitoModeEnabled());
                if (this.mPreferences.getIncognitoModeEnabled()) {
                    ViewUtils.showToast(findViewById(R.id.root_layout), this.getResources().getString(R.string.incognito_on));
                } else {
                    ViewUtils.showToast(findViewById(R.id.root_layout), this.getResources().getString(R.string.incognito_off));
                }

                ViewUtils.setImageTint(this.mPreferences.getIncognitoModeEnabled() ?
                        this.getResources().getColor(R.color.teal)
                        : this.getResources().getColor(R.color.app_color), new ImageView[]{this.mActionIncognito});
                break;
            }
        }

    }

    /**
     * 搜索
     *
     * @param view
     */
    public void onSearchClick(View view) {
        Intent intent = new Intent(this.mContext, BrowserActivity.class);
        intent.putExtra("cmd_search", true);
        this.startActivity(intent);
        overridePendingTransition(0, 0);
    }

    /**
     * 扫码
     *
     * @param view
     */
    public void onTitleBarBtnClick(View view) {
        switch (view.getId()) {
            case R.id.home_scan: {
                BrowserUtils.scanQrCode(this);
                break;
            }
        }
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 9999 && intent != null && (intent.hasExtra("data"))) {
            final String msg = intent.getStringExtra("data");
            new MarkDialog(this).builder()
                    .setTitle(this.getResources().getString(R.string.dialog_message))
                    .setMessage(msg).setCanceledOnTouchOutside(false)
                    .setPositiveButton(this.getResources()
                            .getString(R.string.open_or_search), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                          searchTheWeb(msg);
                            Intent intent = new Intent(MainActivity.this, BrowserActivity.class);
                            intent.putExtra("cmd_scan", true);
                            intent.putExtra("scan_msg", msg);
                            startActivity(intent);
                        }
                    }).setNegativeButton(this.getResources().getString(R.string.action_no), null)
                    .setNeutralButton(this.getResources().getString(R.string.action_copy),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    BrowserUtils.copyText(mContext, msg);
                                }
                            }).show();
        }
    }



    private void switchDayOrNight() {
        ViewUtils.initTheme(getApplication());

        if (mPreferences.getNightModeEnabled()) {//黑夜
//          mHomeSearch.setBackgroundResource(R.drawable.search_box_bg_night);
            ThemeHelper.setTheme(MainActivity.this, ThemeHelper.CARD_LIGHT);
            mHomeBg.setBackgroundColor(ThemeUtils.getColorById(this, R.color.theme_color_primary));
        } else {//白天
            int theme = ThemeHelper.getLastTheme(MainActivity.this);
            ThemeHelper.setTheme(MainActivity.this, theme);//恢复主题
            mHomeSearch.setBackgroundResource(R.drawable.search_box_bg);
            mHomeBg.setBackgroundColor(ThemeUtils.getColorById(this, R.color.theme_color_primary));
        }
//        ViewUtils.setImageTint(mPreferences.getNightModeEnabled() ?
//                        this.getResources().getColor(R.color.app_color)
//                        : this.getResources().getColor(R.color.app_color_dark),
//                new ImageView[]{this.mHomeSerachBt});
//        ViewUtils.setImageTint(mPreferences.getNightModeEnabled() ?
//                        this.getResources().getColor(R.color.app_color)
//                        : this.getResources().getColor(R.color.app_color_dark),
//                new ImageView[]{this.mHomeScan});
        ViewUtils.setImageTint(this.getResources().getColor(R.color.app_color_dark),
                new ImageView[]{this.mHomeSerachBt});
        ViewUtils.setImageTint(this.getResources().getColor(R.color.app_color_dark),
                new ImageView[]{this.mHomeScan});

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            doubleClick2Exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long clickTime = 0;

    private void doubleClick2Exit() {
        if (System.currentTimeMillis() - this.clickTime > 1500) {
            ViewUtils.showToast(findViewById(R.id.root_layout), this.getResources().getString(R.string.message_exit));
            this.clickTime = System.currentTimeMillis();
            return;
        }
        sendExitAppBroadcast();
    }
}
